package webgamemaker.Editor;

import webgamemaker.Common.Callback;

import com.smartgwt.client.widgets.tree.DataChangedEvent;
import com.smartgwt.client.widgets.tree.DataChangedHandler;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;
import com.smartgwt.client.widgets.tree.events.FolderOpenedEvent;
import com.smartgwt.client.widgets.tree.events.FolderOpenedHandler;

public class FileNavigator extends TreeGrid 
{
	public Tree tree;
	public TreeNode rootNode;
	
	public FileNavigator(String baseDir)
	{
		setShowConnectors(true);
		setFields(new TreeGridField("File"));
		
		tree = new Tree();
		rootNode = new TreeNode();
		tree.setRoot(rootNode);
		
		new FileNode(rootNode, baseDir, "", true);
		
		this.addFolderOpenedHandler(new FolderOpenedHandler()
			{
				public void onFolderOpened(FolderOpenedEvent event) 
				{
					if(event.getNode() instanceof FileNode)
					{
						FileNode fileNode  = (FileNode) event.getNode();
						if(!fileNode.loading)
							fileNode.onOpenFolder();
					}
				}
			
			});
		
		setData(tree);
	}
	
	class FileNode extends TreeNode
	{
		public String path;
		public String name;
		public boolean isDir;
		public boolean loading;
		
		public FileNode(TreeNode father, String path, String name, boolean isDir)
		{
			this.path = path;
			this.name = name;
			this.isDir = isDir;
			setAttribute("File", name);
			if(isDir)
			{
				setCanExpand(true);
				setIsFolder(true);
			}
			tree.add(this, father);
		}
		
		public void onOpenFolder()
		{
			if(isDir && !loading)
			{
				loading = true;
				final String newPath = path+(name!=""?("/"+name):"");
				System.out.println(newPath);
				ServerIO.getInstance().readDir(newPath, new Callback()
				{
					public void onCall(Object src) 
					{
						if(src instanceof DirData)
						{
							DirData data = (DirData)src;
							for(String dir : data.dir)
								new FileNode(FileNode.this, newPath, dir, true);
							for(String file : data.file)
								new FileNode(FileNode.this, newPath, file, false);
						}
					}
				});
			}
		}
	}
}
